<template>
    <div class="password-change">
        <c-wrap title="密码修改">
            <mt-field label="用户名" readonly v-model="user.name"></mt-field>
            <mt-field label="旧密码" type="password" placeholder="6-20位字母数字组合" v-model="user.passwordOld"></mt-field>
            <mt-field label="新密码" type="password" placeholder="6-20位字母数字组合" v-model="user.passwordNew"></mt-field>
            <mt-field label="确认密码" type="password" placeholder="6-20位字母数字组合" v-model="user.confirm"></mt-field>
            <mt-button type="primary" style="margin-top: 40px" @click="click">确定</mt-button>
        </c-wrap>
    </div>
</template>
<script>
    import CWrap from '../../components/CWrap'

    export default {
        components: {CWrap},
        data() {
            return {
                user: {
                    name: app.util.localStorage('user.name'),
                    passwordOld: '',
                    passwordNew: '',
                    confirm: ''
                }
            }
        },
        methods: {
            click() {
                if (!this.user.passwordOld || !app.util.validate('password', this.user.passwordOld)) {
                    this.$toast({
                        position: 'top',
                        message: '旧密码输入错误！'
                    });
                    return;
                }
                if (this.user.passwordOld === this.user.passwordNew) {
                    this.$toast({
                        position: 'top',
                        message: '旧密码与新密码不能相同！'
                    });
                    return;
                }
                if (!this.user.passwordNew || !app.util.validate('password', this.user.passwordNew)) {
                    this.$toast({
                        position: 'top',
                        message: '新密码输入错误!'
                    });
                    return;
                }
                if (this.user.passwordNew !== this.user.confirm) {
                    this.$toast({
                        position: 'top',
                        message: '请保持新密码与确认密码一致！'
                    });
                    return;
                }
                app.ajax.put(app.config.api.account.change, {
                    passwordOld: app.util.md5(this.user.passwordOld),
                    passwordNew: app.util.md5(this.user.passwordNew)
                }, (res) => {
                    setTimeout(() => {
                        this.$router.push({path: '/login'});
                    }, 1000);
                });
            }
        }
    }
</script>

